<?php

m2import("model/cart/Article.php");


class model_cart_Cart {

    const SESSION_NAME  = 'wof_articles';
    const MODE_SUM_UP   = 'sumup';
    const MODE_OVERRIDE = 'override';

    private $articles = array();
    private $addmode  = self::MODE_OVERRIDE;

    private static $instance = null;

    private function  __construct($mode = self::MODE_OVERRIDE) {
        $this->addmode = $mode;
        $env = base_ApplicationContext::getInstance()->getEnvWrapper();
        if ($articles = $env->getSession(self::SESSION_NAME)) {
            for ($i=0; $i < count($articles); $i++) {
                $this->articles[] = model_cart_Article::newInstance()->reinit($articles[$i]);
            }
        }
        register_shutdown_function(array($this,"save"));
    }

    public static function getInstance($mode = self::MODE_OVERRIDE) {
        if (self::$instance == null)
            self::$instance = new model_cart_Cart($mode);
        return self::$instance;
    }

    public function getSubTotal () {
        $subtotal = 0;
        for ($i=0; $i < count($this->articles); $i++) {
            $subtotal += $this->articles[$i]->getTotal();
        }
        return $subtotal;
    }

    public function clear () {
        unset($this->articles);
    }

    public function getNumArticles () {
        $numarticles = 0;
        for ($i=0; $i < count($this->articles); $i++) {
            $numarticles += $this->articles[$i]->getQty();
        }
        return $numarticles;
    }

    public function dump() {
        $articles = array();
        for ($i=0; $i < count($this->articles); $i++) {
            $articles[] = $this->articles[$i]->dump();
        }
        return $articles;
    }

    public function save() {
        base_ApplicationContext::getInstance()->getEnvWrapper()->setSession(self::SESSION_NAME, $this->dump());
    }

    /**
     *
     * @param <type> $id
     * @return model_cart_Article
     */
    public function getArticleById($id) {
        for ($i=0; $i < count($this->articles); $i++) {
            if ($this->articles[$i]->getId() == $id) {
                return $this->articles[$i];
            }
        }
        return null;
    }

    public function addArticle($id, $no, $name, $year, $liter, $price, $qty) {
        if ($article = $this->getArticleById($id)) {
            if ($this->addmode == self::MODE_OVERRIDE) {
                $article->setQty($qty);
            } elseif ($this->addmode == self::MODE_SUM_UP) {
                $article->setQty($article->getQty()+$qty);
            }
            return;
        }
        $this->articles[] = new model_cart_Article($id, $no, $name, $year, $liter, $price, $qty);
    }

    public function removeArticle($id) {
        for ($i=0; $i < count($this->articles); $i++) {
            if ($this->articles[$i]->getId() == $id) {
                array_splice($this->articles, $i, 1);
            }
        }
    }

}

?>